package com.xiaow.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.xiaow.common.utils.JwtUtils;
import com.xiaow.common.vo.Result;

import com.xiaow.gateway.service.AccountService;
import io.jsonwebtoken.Claims;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    AccountService accountService;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径
        String path = request.getPath().toString();

        //判断是否访问的路径可以不认证的形式访问
        List<String> noAuthUrls = accountService.getNoAuthUrls();
        for (String noAuthUrl : noAuthUrls) {
            if (path.contains(noAuthUrl)) {
                return chain.filter(exchange);
            }
        }


        List<String> tokenList = exchange.getRequest().getHeaders().get("token");

        if (CollectionUtils.isEmpty(tokenList) || tokenList.get(0).trim().isEmpty()) {
            // 错误信息
            byte[] data = new byte[0];
            try {
                data = new ObjectMapper().writeValueAsBytes(Result.result("Token is null", 401, null));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return response.writeWith(Mono.just(buffer));
        } else {
            try {
                String s = tokenList.get(0);
                Claims claims = JwtUtils.getClaims(s);
                List<String> urls = (List<String>) claims.get("urls");
                for (String url : urls) {
                    if (path.contains(url)) {
                        return chain.filter(exchange);
                    }
                }

            } catch (Exception e) {

            }

        }

        byte[] data = new ObjectMapper().writeValueAsBytes(Result.result("没有权限访问", 401, null));
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 优先级
     * 权值越小优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
